import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import InBoundView from "@/views/InBoundView.vue";
import OutBoundView from "@/views/OutBoundView.vue";
import BusinessView from "@/views/BusinessView.vue";
import LoginView from "@/views/LoginView.vue";
import RegisterView from "@/views/RegisterView.vue";

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'register',
    component: RegisterView
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/InBound',
    name: 'inbound',
    component: InBoundView,
    meta: { requiresAuth: true }
  },
  {
    path: '/OutBound',
    name: 'outbound',
    component: OutBoundView,
    meta: { requiresAuth: true }
  },
  {
    path: '/Business',
    name: 'Business',
    component: BusinessView,
    meta: { requiresAuth: true }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要登录的页面
    if (!isLoggedIn) {
      next('/login')
    } else {
      next()
    }
  } else {
    // 不需要登录的页面（如登录页、注册页）
    if (isLoggedIn && (to.path === '/login' || to.path === '/register')) {
      // 已登录用户访问登录页或注册页，重定向到首页
      next('/')
    } else {
      next()
    }
  }
})

export default router
